const redis = require("redis")
const { redisConfig } = require("../config/config")
const redisClient = redis.createClient(redisConfig)

// 创建redis客户端
redisClient.on("error", (err) => {
  console.error("on :", err);
})

// set
const set = (key, value) => {
  if (typeof value === "object") {
    value = JSON.stringify(value)
  }
  redisClient.set(key, value)
}

const get = (key) => {
  const promise = new Promise((resolve, reject) => {
    redisClient.get(key, (err, reply) => {
      if (err) {
        reject(err)
        return
      }
      if (reply == null) {
        resolve(null)
        return
      }
      try {
        resolve(JSON.parse(reply))
      } catch (ex) {
        resolve(reply)
      }
    })
  })
  return promise
}

module.exports = {
  set,
  get
}
